package com.TheyChat.service.socket;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.TheyChat.service.config.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/TheyChat/Group/{groupId}/{userId}")
public class GroupSocketServer {
    private static ConcurrentHashMap<String, ConcurrentHashMap<String, Session>> webSocketMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("groupId") String groupId, @PathParam("username") String username) {
        if (StrUtil.isBlank(groupId))
            throw new BusinessException("群组id位空");
        if (StrUtil.isBlank(username))
            throw new BusinessException("用户名位空");
        ConcurrentHashMap<String, Session> map = webSocketMap.get(groupId);
        if (ObjectUtil.isEmpty(map)) {
            map = new ConcurrentHashMap<>();
        }
        map.put(username, session);
        webSocketMap.put(groupId,map);
        System.out.println("用户"+username+"连接群组"+groupId+"成功");
    }
}
